<?php
include("xmlimporter/XMLImporter.php");
include("dao/XMLFeedDAO.php");
include("dao/DatabaseDAO.php");

$userId = $_GET["UserId"];
$xmlFeedId = $_GET["xmlFeedId"];

$xmlFeedDAO = new XMLFeedDAO();
$databaseDAO = new DatabaseDAO();

$xmlFeed = $xmlFeedDAO->getXMLFeed($xmlFeedId);
$database = $databaseDAO->getDatabase($xmlFeed["DatabaseId"]);
$xmlTableMapping = $xmlFeedDAO->getPrimaryXMLTableMapping($xmlFeedId);
$xmlSecondaryTableMapping = $xmlFeedDAO->getSecondaryXMLTableMapping($xmlFeedId);
$xmlColumnMappingList = $xmlFeedDAO->getXMLColumnMapping($xmlTableMapping["Id"]);
$keyColumn = $xmlFeedDAO->getKeyColumn($xmlFeedId);

$dbConfig = Array
(
    'dbtype' => "MYSQL",
    'host' => $database["URL"],
    'database' => $database["DatabaseName"],
    'user' => $database["User"],
    'password' => $database["Password"]
);

$fieldsMap = XMLImporter::getFieldsMap($xmlColumnMappingList, $xmlFeedDAO);
set_time_limit(3000);
$xmlImporter = new XMLImporter($dbConfig, $fieldsMap, $xmlFeed["URL"], $xmlFeed["DownloadFilesFolder"], $xmlFeed["XmlRootItem"]);
list($uniqueItems, $firstItemId, $lastItemId) = $xmlImporter->parseLargeFile($xmlTableMapping["Table"], $keyColumn);

for ($i = 0; $i < count($xmlSecondaryTableMapping); $i++) {
    $xmlSecondaryColumnMappingList = $xmlFeedDAO->getXMLColumnMapping($xmlSecondaryTableMapping[$i]["Id"]);
    $fieldsMap = XMLImporter::getFieldsMap($xmlSecondaryColumnMappingList, $xmlFeedDAO);
    $uniqueItemsCopy = $xmlImporter->copyArray($uniqueItems);
    $table = $xmlSecondaryTableMapping[$i]["Table"];
    $xmlImporter->mapAdditionalTable($uniqueItemsCopy, $firstItemId, $lastItemId, $fieldsMap, $table, $keyColumn);
}

$xmlFeedDAO->updateLastRunDate($xmlFeedId);
?>